package com.lab.idea.bl.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.lab.idea.bl.entity.ExcelOut;
import com.lab.idea.bl.mapper.ExcelOutMapper;
import com.lab.idea.bl.service.*;
import com.lab.idea.common.exception.LabException;
import com.lab.idea.common.query.LabQuery;
import com.lab.idea.mybatis.service.impl.LabServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 输出配置 服务实现类
 * </p>
 *
 * @author lab
 * @since 2023-11-06
 */
@Service
public class ExcelOutServiceImpl extends LabServiceImpl<ExcelOutMapper, ExcelOut> implements ExcelOutService {

    @Autowired
    private ExcelFilterService excelFilterService;

    @Autowired
    private ExcelJoinService excelJoinService;

    @Autowired
    private ExcelColumnService excelColumnService;

    @Autowired
    private ExcelDocxService excelDocxService;

    @Override
    protected boolean saveCheck(ExcelOut entity) {
        if (StrUtil.isBlankIfStr(entity.getExcelId())) {
            throw new LabException("请选择模板");
        }
        if (StrUtil.isBlankIfStr(entity.getOutName())) {
            throw new LabException("输出名称为空");
        }
        LabQuery labQuery = new LabQuery();
        labQuery.eq("outName",entity.getOutName()).eq("excelId",entity.getExcelId());
        List<ExcelOut> list = query(labQuery);
        if (!CollUtil.isEmpty(list)) {
            for (ExcelOut excelOut : list) {
                if (!StrUtil.equals(excelOut.getOutId(),entity.getOutId())) {
                    throw new LabException(String.format("%s 已经存在",entity.getOutName()));
                }
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = LabException.class)
    public boolean removeById(Serializable id) {
        if (super.removeById(id)) {
            LabQuery labQuery = new LabQuery().setPageSize(-1);
            labQuery.eq("outId",id.toString());
            excelFilterService.remove(labQuery);
            excelJoinService.remove(labQuery);
            excelColumnService.remove(labQuery);
            excelDocxService.remove(labQuery);
            return true;
        }
        return false;
    }
}
